<template>
    <div>
        <loginTop title="注册">
            <div slot="right" @click="$router.push('/login')">登录</div>
        </loginTop>
        <loginText label="用户名" placeholder="用户名不少于2个字符" style="margin: 15px 0"
                   @inputChange="content=> params.name =content"></loginText> <!--和事件绑定的方法不需要带()-->
        <loginText label="密码" type="password" placeholder="密码不少于8个字符"
                   @inputChange="content=> params.password =content"></loginText>
        <loginText label="电话" placeholder="电话"
                   @inputChange="content=> params.telephone =content"></loginText>
        <van-field
                v-model="params.code"
                center
                clearable
                label="短信验证码"
                placeholder="请输入短信验证码"
        >
            <template #button>
                <van-button size="small" type="primary" @click="getCode">发送验证码</van-button>
            </template>
        </van-field>
        <login-btn text="注册" @registerSubmit="register"></login-btn>
    </div>
</template>
<script>
    import navbar from "@/components/common/navbar";

    import loginTop from "@/components/common/loginTop.vue"
    import loginText from "@/components/common/loginText.vue";
    import loginBtn from "@/components/common/loginBtn";
    import Navbar from "@/components/common/navbar";

    export default {
        data() {
            return {
                params: {name: '', password: '', telephone: "", code: ""}
            }
        },
        name: "register",
        components: {
            Navbar,
            loginTop,
            loginText,
            loginBtn
        },
        methods: {
            getCode() {
                if (!(/^1[3456789]\d{9}$/.test(this.params.telephone))) {
                    this.$msg.fail("手机号码有误，请重填");
                    return false;
                }
                this.$http.get("/user/getAuthCode", {params: {telephone: this.params.telephone}})

            },
            successInp(content) { // 这个content是在 loginText里面发送的事件 附带的值
                console.log(content)
            },
            async register() {
                const rule = RegExp("^.{2,16}$")
                const rule2 = RegExp("^.{8,16}$")

                if (rule.test(this.params.name) && rule2.test(this.params.password)) {
                    const res = await this.$http.post('/user/signUp', this.params)
                    this.$msg.fail(res.data.message)
                    if (res.data.code == 0) {
                        localStorage.setItem("token", res.data.data.token)
                        setTimeout(() => {
                            this.$router.push("/")
                        }, 1000)
                    }
                } else {
                    this.$msg.fail("格式不正确")
                }
            }
        }
    }
</script>

<style lang="less">
    /*loginText {*/
    /*    margin: 4.17vw;*/
    /*}*/
</style>